import { defineStore } from 'pinia';

export const useCartStore = defineStore('cart', {
    state: () => ({
        items: [],
        itemCount: 0
    }),
    actions: {
        addItem(item) {
            const existingItem = this.items.find(i => i.id === item.id);
            if (existingItem) {
                existingItem.number += item.number;
            } else {
                this.items.push(item);
            }
            this.itemCount = this.items.reduce((count, item) => count + item.number, 0);
        },
        removeItem(itemId) {
            this.items = this.items.filter(item => item.id !== itemId);
            this.itemCount = this.items.reduce((count, item) => count + item.number, 0);
        },
        clearCart() {
            this.items = [];
            this.itemCount = 0;
        }
    },
    getters: {
        totalPrice: (state) => {
            return state.items.reduce((total, item) => total + item.price * item.number, 0);
        },
        computedItemCount: (state) => {
            return state.itemCount;
        }
    }
},{
    persist:true
});